// pages/detail-poster-shaer/index.js
import api from '../../api/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    path: '',
    detail: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      detail: JSON.parse(options.detail)
    })
    console.log(this.data.detail)
    if (this.data.detail) {
      this.getHouseSharePoster();
    }

  },
  //获取小程序码
  getHouseSharePoster() {
    api.getHouseSharePoster(this.data.detail.id).then(res => {
      let data = res.data.data;
      //声明系统文件
      let fs = wx.getFileSystemManager();
      let times = new Date().getTime();
      let codeImg = wx.env.USER_DATA_PATH + '/' + times + '.jpg';
      //写入图片
      fs.writeFile({
        filePath: codeImg,
        data: data.slice(22),
        encoding: 'base64',
        success: () => {
          this.setData({
            path: codeImg
          })
          console.log('111', this.data.path);
          this.draw();

        }
      })


    })
  },
  count: 0, //图片加载计数
  clicked: false, //点击了保存
  canvas: null,
  draw() {
    const query = wx.createSelectorQuery();
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        this.canvas = canvas;
        const ctx = canvas.getContext('2d')
        canvas.width = 650;
        canvas.height = 960;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);




        //绘制banner
        const drawBanner = (src, startX, startY, width, height) => {
          let img = canvas.createImage();
          img.src = src;
          img.onload = (res) => {
            console.log()
            ctx.drawImage(img, startX, startY, width, height)
            this.count++
            if (this.count == 3 && this.clicked == true) {
              wx.hideLoading();
              this.save();
            }
          }
        }
        drawBanner(this.data.detail.images[0], 30, 30, 290, 360)
        drawBanner(this.data.detail.images[1], 330, 30, 290, 175)
        drawBanner(this.data.detail.images[2], 330, 215, 290, 175)




        ctx.font = "bold 32px MicrosoftYaHei-Bold";
        ctx.fillStyle = "#333333";
        var str = this.data.detail.title;
        var lineWidth = 0;
        var canvasWidth = canvas.width - 60; //计算canvas的宽度
        var initHeight = 440; //绘制字体距离canvas顶部初始的高度
        var lastSubStrIndex = 0; //每次开始截取的字符串的索引
        for (let i = 0; i < str.length; i++) {
          lineWidth += ctx.measureText(str[i]).width;
          if (lineWidth > canvasWidth) {
            ctx.fillText(str.substring(lastSubStrIndex, i), 30, initHeight); //绘制截取部分
            initHeight += 50; //20为字体的高度
            lineWidth = 0;
            lastSubStrIndex = i;
          }
          if (i == str.length - 1) { //绘制剩余部分
            ctx.fillText(str.substring(lastSubStrIndex, i + 1), 30, initHeight);
          }

        }


        ctx.font = "22px MicrosoftYaHei";
        ctx.fillText(this.data.detail.tbHouse.posterDescribe, 30, 540);
        // 绘制标签
        var arrlable = [this.data.detail.tbHouse.houseArea + 'm²', this.data.detail.tbHouse.houseType, this.data.detail.tbHouse.decorate, this.data.detail.tbHouse.type, this.data.detail.tbHouse.age + '年'];
        //初始左边位置
        let left = 30;
        arrlable.forEach(drawLabel)

        function drawLabel(text) {
          ctx.font = '22px MicrosoftYaHei'
          //获取文字宽度
          const metrics = ctx.measureText(text)
          //文字据左右两边的距离
          let padding = 12
          //每个块的宽度
          let itemWidth = metrics.width + padding * 2
          ctx.beginPath()
          //画背景
          ctx.fillStyle = '#EEEEFE';
          ctx.fillRect(left, 570, itemWidth, 40)
          //画文字
          ctx.fillStyle = '#585CF7'
          ctx.fillText(text, left + padding, 600)
          ctx.closePath()
          // +10是两个块之间的间距
          left += itemWidth + 10
        }

        /**
         * 绘制文字
         * @param {*} font 字体样式
         * @param {*} fillStyle 字体颜色
         * @param {*} content 内容
         * @param {*} startX 开始位置x
         * @param {*} startY 开始位置y
         */
        const drawText = (font, fillStyle, content, startX, startY) => {
          ctx.font = font;
          ctx.fillStyle = fillStyle;
          ctx.fillText(content, startX, startY);
          return ctx.measureText(content).width
        }

        let textWidth = 0
        //起拍价
        textWidth = drawText("bold 38px PingFang-SC-Heavy", '#FC4073', this.data.detail.tbHouse.origin, 30, 675)
        //起拍价单位
        drawText("24px PingFang-SC-Heavy", '#FC4073', '万', textWidth + 35, 675)
        drawText("22px PingFang-SC-Heavy", '#333333', '起拍价', 30, 715)
        drawText("20px PingFang-SC-Heavy", '#999999', '（起拍时间：' + this.data.detail.tbHouse.auctionTime + '）', 105, 715)







        // 市场价
        ctx.fillStyle = "#999999";
        ctx.font = "24px PingFang-SC-Heavy";
        textWidth = ctx.measureText('万').width;
        var textX = canvas.width - textWidth - 30;
        ctx.fillText('万', textX, 675);


        ctx.font = "38px PingFang-SC-Heavy";
        var priWidth = ctx.measureText(this.data.detail.tbHouse.housePrice).width;
        var prX = canvas.width - 30 - textWidth - priWidth - 10;
        ctx.fillText(this.data.detail.tbHouse.housePrice, prX, 675)
        //绘制中划线
        ctx.moveTo(prX, 660); //设置线条的起始路径坐标
        ctx.lineTo(textX, 665); //设置线条的终点路径坐标
        ctx.lineWidth = '3';
        ctx.strokeStyle = "#999999";
        ctx.stroke(); //对当前路径进行描边
        ctx.font = "22px PingFang-SC-Heavy";
        var scjWidth = ctx.measureText('市场价').width;
        var scjX = prX + (priWidth + textWidth) / 2 - (scjWidth / 2); //价格的X+ （价格的宽+单位的宽）/2-（自身的宽/2） 
        ctx.fillText('市场价', scjX, 715);
        //分割线

        ctx.beginPath();
        ctx.arc(-10, 780, 30, 0, Math.PI * 2, 1);
        ctx.closePath();
        ctx.fillStyle = '#F5F5F5';
        ctx.lineWidth = 1;
        ctx.fill();

        ctx.beginPath();
        ctx.arc(canvas.width + 10, 780, 30, 0, Math.PI * 2, 1);
        ctx.closePath();
        ctx.fillStyle = '#F5F5F5';
        ctx.fill();

        ctx.beginPath();
        ctx.setLineDash([10, 20], 5);
        ctx.moveTo(50, 780); //设置线条的起始路径坐标
        ctx.lineTo(canvas.width - 50, 780); //设置线条的终点路径坐标
        ctx.closePath();
        ctx.strokeStyle = "#DDDDDD";
        ctx.stroke(); //对当前路径进行描边

        // 小程序码
        let img = canvas.createImage();
        img.onload = () => {
          ctx.drawImage(img, 30, 810, 120, 120)
        }
        img.src = this.data.path;



        // 扫码文案
        drawText("30px PingFang-SC-Medium", "#333333", '扫码查看更多优质房源', 190, 860)
        drawText("24px PingFang-SC-Medium", "#999999", '专业团队配合房源尽调，法拍房零风险', 190, 910)

        // ctx.draw();


      })
  },


  save() {
    this.clicked = true
    if (this.count == 3) {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        canvas: this.canvas,
        width: 650,
        height: 960,
        success: (res) => {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                icon: 'none',
                title: '保存成功',
              })
            },
            fail(err) {
              console.log(err)
            },
          })
        },
        fail: function (res) {
          console.log(res);
        }
      });

    } else {
      wx.showLoading({
        title: '海报生成中',
        mask: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})